package com.example.androidmqtt.Service.ServiceImpl.ServiceImpl;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.androidmqtt.Entry.*;
import com.example.androidmqtt.Mapper.*;
import com.example.androidmqtt.Service.ServiceImpl.UserService;
import com.example.androidmqtt.Vo.UserMessage;
import com.example.androidmqtt.Vo.UserMore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileSystemUtils;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author: pjg
 * @time: 2022/9/13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String FILE_PATH = "D:\\File\\Android\\AndroidMqtt\\src\\main\\resources\\static\\avatar\\";
    @Resource
    private UserMapper userMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private MessageMapper messageMapper;

    @Override
    public UserMore Login(String account, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", account);
        User user = userMapper.selectOne(queryWrapper);
        //密码应该加密
        if (user != null && user.getUserPassword().equals(SecureUtil.md5(password))) {
            Department one = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_id", user.getUserDepartment()));
            return new UserMore(user.getUserId(), user.getUserName(), user.getUserAvatar(), one.getTag(), one.getDepartmentName());
        }
        return null;
    }

    @Override
    public int Register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user.getUserName());
        User one = userMapper.selectOne(queryWrapper);
        //存在用户
        if (one != null) return -1;
        user.setUserPassword(SecureUtil.md5(user.getUserPassword()));
        return userMapper.insert(user);
    }

    @Override
    public int Register(String userName, String userPassword, Integer userDepartment) {
        User user = new User(userName, "", userPassword, userDepartment);
        return Register(user);
    }

    @Override
    public int ChangeInfo(User user) {
        try {
            //删除旧的头像
            if (user.getUserAvatar() != null) {
                String userAvatar1 = userMapper.getUserAvatar(user.getUserId());
                File[] files = new File(FILE_PATH).listFiles();
                assert files != null;
                for (File per : files) {
                    if (per.getName().equals(userAvatar1)) {
                        FileSystemUtils.deleteRecursively(per);
                        break;
                    }
                }
            }

            if (user.getUserPassword() != null)
                user.setUserPassword(SecureUtil.md5((user.getUserPassword())));

            return userMapper.updateById(user);
        } catch (Exception e) {
            //不可参数均为空
            return 0;
        }
    }

    @Transactional
    @Override
    public int DeleteUser(Integer userId) {
        return userMapper.DeleteUser(userId);
    }

    //获取用户所有消息列表
    @Override
    public List<UserMessage> getUserMessage(Integer userId) {
        ArrayList<UserMessage> userMessage = messageMapper.getReadMessage(userId);

        try {
            //时间格式化
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date nowTime = format.parse(format.format(new Date()));
            userMessage.forEach(per -> {
                try {
                    Date pubTime = format.parse(per.getNewsPublishTime());
                    //计算与当前时间的时间差（分钟）
                    int between = (int) DateUtil.between(pubTime, nowTime, DateUnit.MINUTE);
                    String diff = between / 1440 >= 1 ? "" + between / 1440 + "天前" :
                            between / 60 >= 1 ? "" + between / 60 + "小时前" :
                                    between >= 1 ? "" + between + "分钟前" : "刚刚";
                    per.setNewsPublishTime(diff);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return userMessage.isEmpty() ? null : userMessage;
    }

    @Override
    public int setMessageRead(Integer userId, Integer newsId) {
        Message one = messageMapper.selectOne(new QueryWrapper<Message>().eq("user_id", userId).eq("news_id", newsId));
        one.setIsRead(1);
        return messageMapper.update(one, new QueryWrapper<Message>().eq("user_id", userId).eq("news_id", newsId));
    }

}
